package com.example.indenture.user.service.impl;


import com.example.indenture.common.Constant;
import com.example.indenture.common.vo.Result;
import com.example.indenture.common.vo.Search;
import com.example.indenture.user.dao.UserDao;
import com.example.indenture.user.entity.User;
import com.example.indenture.user.service.UserService;
import com.example.indenture.util.FaceComparison;
import com.example.indenture.util.PasswordUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.Optional;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;

    @Override
    @Transactional
    public Result<User> insertUser(User user,HttpSession session) {
        // 根据用户名查询用户是否存在，存在返回错误消息，不存在继续插入
        User temp = userDao.getUserByUserName(user.getUserName());
        if (temp != null) {
            return Result.failed("用户名重复。");
        }
        User temp1 = userDao.getUserByEmail(user.getEmail());
        if (temp1 != null) {
            return Result.failed("邮箱重复。");
        }
        User temp2 = userDao.getUserByPhone(user.getPhone());
        if (temp2 != null) {
            return Result.failed("电话重复。");
        }

        // 初始化 user 某些属性
        user.setCreateDate(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        user.setPassword(PasswordUtil.encrypt(user.getPassword()));
        // 插入 user
        userDao.insertUser(user);
        //存储Session
        session.setAttribute(Constant.SESSION_USERINFO_KEY, user);
        // 返回结果
        return Result.ok(user);
    }

    @Override
    @Transactional
    public Result<Object> deleteUserById(int id) {
        // 删除对应user
        userDao.deleteUserById(id);
        // 返回结果
        return Result.ok();
    }

    @Override
    @Transactional
    public Result<Object> updateUser(User user) {
        // 根据用户名查询用户是否存在，判断是否和别人的名字一样，相同则返回错误信息
        User temp = userDao.getUserByUserName(user.getUserName());
        if (temp != null && temp.getId() != user.getId()) {
            return Result.failed("用户名重复。");
        }
        User temp1 = userDao.getUserByEmail(user.getEmail());
        if (temp1 != null && temp1.getId() != user.getId()) {
            return Result.failed("邮箱重复。");
        }
        User temp2 = userDao.getUserByPhone(user.getPhone());
        if (temp2 != null && temp2.getId() != user.getId()) {
            return Result.failed("电话重复。");
        }
        // 初始化 user 相关属性
        user.setUpdateTime(LocalDateTime.now());
        user.setPassword(PasswordUtil.encrypt(user.getPassword()));
        // 进行更新操作
        userDao.updateUser(user);
        // 返回正确的结果
        return Result.ok();
    }

     @Override
    @Transactional
    public Result<User> loginInUser(String username, String password, HttpSession httpSession) {
        if (!org.springframework.util.StringUtils.hasLength(username) || !StringUtils.hasLength(password)) {
            return Result.failed("用户名或者密码为空!"); // 如果用户名或密码为空，将返回一个包含错误信息的Result对象，提示用户名或密码为空。
        }
        //根据用户名去得到盐值
        final User user = userDao.getPasswordByName(username);
        System.out.println(user);
        if (PasswordUtil.decrypt(password, user.getPassword())) {
            // 使用PasswordUtil工具类的decrypt方法，将输入的密码和从数据库中获取的密码进行比较，检查密码是否匹配。
            httpSession.setAttribute(Constant.SESSION_USERINFO_KEY, user);
            // 将用户对象的密码字段设为空字符串，以避免将密码信息传递到客户端。
            user.setPassword("");
            return Result.ok(user); //如果验证成功，将返回一个包含成功信息和用户对象的Result对象。
        } else {
            return Result.failed("验证失败!");
        }
    }

    @Override
    @Transactional
    public Result<User> loginByUserFace(String username, String validPhoto,HttpSession httpSession) throws Exception {
        if (!org.springframework.util.StringUtils.hasLength(username)) {
            return Result.failed("用户名为空!");
        }
        final User user = userDao.getUserByUserName(username);
        String userHead = user.getUrl();
        FaceComparison faceComparison = new FaceComparison(); //初始化识别器
        float confidence = faceComparison.Recognize(userHead, validPhoto);  //调用人脸比对方法
        if (confidence > 75f) {
            user.setPassword("");
            httpSession.setAttribute(Constant.SESSION_USERINFO_KEY, user);
            return Result.ok(user); //如果验证成功，将返回一个包含成功信息和用户对象的Result对象。
        } else {
            return Result.failed("面部特征不匹配!");
        }
    }

    @Override
    @Transactional
    public Result<Object> updateUserUrl(int id, String url) {
        userDao.updateUserUrl(id, url);
        // 返回结果
        return Result.ok();
    }

    @Override
    public PageInfo<User> getUsersBySearch(Search search) {
        search.initSearch();
        PageHelper.startPage(search.getCurrentPage(), search.getPageSize());
        return new PageInfo<>(Optional
                .ofNullable(userDao.getUsersBySearch(search))
                .orElse(Collections.emptyList()));
    }

    @Override
    public Result<Integer> getIdByName(String keyword) {
        Integer id = null;
        id = userDao.getIdByName(keyword);
        if (id == null) {
            return Result.failed("该老师不存在！");
        }
        return Result.ok(id);
    }

    @Override
    public User getUseById(Integer id) {
        return userDao.getUserById2(id);
    }

}
